//axios的基础封装
import axios from "axios"
import axiosAdapterUniapp from 'axios-adapter-uniapp'
import { useUserStore } from "../stores/userStore";

const httpInstance = axios.create({
  baseURL: 'http://localhost:6060',
  timeout: 5000,
//   uniapp使用axios需要添加适配器
  adapter: axiosAdapterUniapp
})

// 定义一个数组，包含所有不需要拦截的路径
const noInterceptPaths = [
  '/user/login',
  '/user/id',
  '/user/reg',
  '/user/forget',
  'https://api.weixin.qq.com/sns/jscode2session',
  'http://127.0.0.1:6999/change/getHtml',
];

// // axios请求拦截器
httpInstance.interceptors.request.use((config) => {
  const userStore = useUserStore();
  // 如果在不需要拦截的路径中，直接返回配置
  if (noInterceptPaths.some(path => config.url === path)) {
    return config;
  }
  // 从localStorage获取token
  const token = uni.getStorageSync('token');
  // 如果token存在，则添加到请求头中
  if (token) {
    config.headers['token'] = token;
  }else{
    // 先登录
    userStore.clearUserInfo();
    uni.navigateTo({
      url:'/pages/login/login'
    })
  }
  return config
}, e => Promise.reject(e))

// axios响应式拦截器
// 只对出错的进行处理
httpInstance.interceptors.response.use((res) => {
  return res.data
},error => {
  // 错误处理逻辑
  if (error.response.status === 401) { 
    uni.clearStorageSync('token')
    uni.navigateTo({
      url:'/pages/login/login'
    })
  }
  
  return Promise.reject(error);
})

export default httpInstance